package com.miyuan.view.login;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.miyuan.R;
import com.miyuan.base.BaseActivity;
import com.miyuan.bean.ResultBean;
import com.miyuan.bean.request.LoginParam;
import com.miyuan.bean.request.SMSParam;
import com.miyuan.bean.respone.TokenBean;
import com.miyuan.bean.respone.UserBean;
import com.miyuan.net.NetService;
import com.miyuan.net.RetrofitClient;
import com.miyuan.utils.NetworkUtils;
import com.miyuan.utils.SPUtils;
import com.miyuan.view.home.HomeActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 登录注册
 */

public class LoginControlActivity extends BaseActivity {
    @BindView(R.id.phone_num_edit)
    EditText phoneNumEdit;
    @BindView(R.id.verify_code_edit)
    EditText verifyCodeEdit;
    @BindView(R.id.send_verify_code)
    TextView sendVerifyCode;
    @BindView(R.id.login_btn)
    TextView loginBtn;
    @BindView(R.id.login_btn_arrow)
    ImageView loginBtnArrow;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setLayout(R.layout.activity_login);
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        loginBtn.setEnabled(false);
    }

    @OnClick(R.id.login_btn)
    public void login() {
        String ip = NetworkUtils.getIPAddress(true);
        if (ip != null) {
            String phoneNum = phoneNumEdit.getText().toString().trim();
            String verifyCode = verifyCodeEdit.getText().toString().trim();

            RetrofitClient.getInstance()
                    .create(NetService.class)
                    .login(new LoginParam(phoneNum, verifyCode, ip).toRequestBody())
                    .enqueue(new Callback<ResultBean<TokenBean>>() {
                        @Override
                        public void onResponse(Call<ResultBean<TokenBean>> call, Response<ResultBean<TokenBean>> response) {
                            ResultBean<TokenBean> resultBean = response.body();
                            if (resultBean.getData() != null) {
                                TokenBean tokenBean = resultBean.getData();
                                if (tokenBean.access_token != null) {
                                    SPUtils.getInstance().put("Authorization", tokenBean.access_token);
//                                    SPUtils.getInstance().put("Authorization", "c265eb4d-1de1-4f0e-91e3-33591a1bb293");
                                    SPUtils.getInstance().put("expire_in", tokenBean.expires_in);
                                    SPUtils.getInstance().put("token_type", tokenBean.token_type);
                                    RetrofitClient.getInstance()
                                            .create(NetService.class)
                                            .getUserInfo()
                                            .enqueue(new Callback<ResultBean<UserBean>>() {
                                                @Override
                                                public void onResponse(Call<ResultBean<UserBean>> call, Response<ResultBean<UserBean>> response) {
                                                    ResultBean<UserBean> resultBean = response.body();
                                                    if (resultBean.getData() != null) {
                                                        UserBean userBean = resultBean.getData();
                                                        SPUtils.getInstance().put("userId", userBean.getId());
                                                    } else {
                                                        Toast.makeText(LoginControlActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                                                    }
                                                }

                                                @Override
                                                public void onFailure(Call<ResultBean<UserBean>> call, Throwable t) {

                                                }

                                            });
                                    startActivity(new Intent(LoginControlActivity.this, HomeActivity.class));
                                    finish();
                                }
                            } else {
                                Toast.makeText(LoginControlActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultBean<TokenBean>> call, Throwable t) {

                        }
                    });
        } else {
            Toast.makeText(LoginControlActivity.this, "请检查网络连接", Toast.LENGTH_SHORT).show();
        }

    }

    @OnClick(R.id.send_verify_code)
    public void sendVerifyCode() {
        String phoneNum = phoneNumEdit.getText().toString().trim();
        if (phoneNum.length() > 0) {
            RetrofitClient.getInstance()
                    .create(NetService.class)
                    .getSMSCode(new SMSParam(phoneNum).toRequestBody())
                    .enqueue(new Callback<ResultBean>() {
                        @Override
                        public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                            ResultBean resultBean = response.body();
                            if (resultBean.getMsg().equals("成功")) {
                                Toast.makeText(LoginControlActivity.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                                sendVerifyCode.setEnabled(false);
                                Flowable.intervalRange(0, 120, 0, 1, TimeUnit.SECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext(new Consumer<Long>() {
                                            @Override
                                            public void accept(Long aLong) throws Exception {
                                                sendVerifyCode.setText("发送验证码(" + (120 - aLong) + ")");
                                                sendVerifyCode.setTextColor(Color.parseColor("#666666"));
                                            }
                                        })
                                        .doOnComplete(new Action() {
                                            @Override
                                            public void run() throws Exception {
                                                //倒计时完毕置为可点击状态
                                                sendVerifyCode.setEnabled(true);
                                                sendVerifyCode.setText("获取验证码");
                                            }
                                        })
                                        .subscribe();
                            } else {
                                Toast.makeText(LoginControlActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                                sendVerifyCode.setEnabled(true);
                                sendVerifyCode.setText("重发验证码");
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultBean> call, Throwable t) {
                            Toast.makeText(LoginControlActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                            sendVerifyCode.setEnabled(true);
                            sendVerifyCode.setText("重发验证码");
                        }
                    });

        } else {
            Toast.makeText(LoginControlActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
        }

    }

    @OnTextChanged(value = R.id.phone_num_edit, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onPhoneNumChanged(Editable s) {
        if (verifyCodeEdit.getText().toString().trim().length() > 0 && s.toString().trim().length() > 0) {
            loginBtn.setBackgroundResource(R.mipmap.login_btn_deep);
            loginBtn.setEnabled(true);
            loginBtnArrow.setVisibility(View.GONE);
        } else {
            loginBtn.setBackgroundResource(R.mipmap.login_btn);
            loginBtn.setEnabled(false);
            loginBtnArrow.setVisibility(View.VISIBLE);
        }
    }

    @OnTextChanged(value = R.id.verify_code_edit, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onVerifyCodeChanged(Editable s) {
        if (s.toString().trim().length() > 0 && phoneNumEdit.getText().toString().trim().length() > 0) {
            loginBtn.setBackgroundResource(R.mipmap.login_btn_deep);
            loginBtn.setEnabled(true);
            loginBtnArrow.setVisibility(View.GONE);
        } else {
            loginBtn.setBackgroundResource(R.mipmap.login_btn);
            loginBtn.setEnabled(false);
            loginBtnArrow.setVisibility(View.VISIBLE);
        }
    }
}
